package com.juno.cafenoa.member;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.juno.cafenoa.Constants;
import com.juno.cafenoa.MainActivity;
import com.juno.cafenoa.R;
import com.juno.cafenoa.TopNavigatorView;
import com.juno.cafenoa.mypage.PasswordActivity;
import com.juno.cafenoa.net.AsyncTaskCompleteListener;
import com.juno.cafenoa.net.HttpPostTask;
import com.juno.cafenoa.util.CafeNoaPreference;
import com.juno.cafenoa.util.Util;

/**
 * 회원가입 Activity
 * @author JUNHO
 */
public class AccountMakeActivity extends Activity implements OnClickListener, OnTouchListener {
	private EditText etID;
	private EditText etPass;
	private EditText etPhone;
	
	private Button btnRegedit;
	private Button btnClear;
	
	private Context mContext;
	
	TopNavigatorView navi;

		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_regedit);
		etID = (EditText) findViewById(R.id.regedit_id);
		etPass = (EditText) findViewById(R.id.regedit_password);
		etPhone = (EditText) findViewById(R.id.regedit_phoneNumber);
		
		navi = (TopNavigatorView) findViewById(R.id.navi_regedit);
		navi.init("회원가입");
		etPass.setOnTouchListener(this);
		
		btnRegedit = (Button) findViewById(R.id.regedit_btn);
		btnClear = (Button)findViewById(R.id.regedit_clear_btn);
		
		btnRegedit.setOnClickListener(this);
		btnClear.setOnClickListener(this);
		
		etPhone.setText(Util.getPhoneNum(this));
		
	}

	@Override
	public void onClick(View v) {
		if(v==btnRegedit){
			//서버와 통신
			registListener.excuteHttpTask();
		} else if(v==btnClear){
			etID.setText("");
			etPass.setText("");
			etPhone.setText("");
		}
	}
	
	@Override
	public boolean onTouch(View v, MotionEvent ev) {
		if(v==etPass && ev.getAction()==MotionEvent.ACTION_DOWN){
			//패스워드  EditText 터치시.
			Intent intent = new Intent(mContext, PasswordActivity.class);
			intent.putExtra(Constants.USER_PASSWORD_MODE_SET, Constants.PASSWORD_SET_REGEDIT);
			startActivityForResult(intent, Constants.REQUEST_PASSWORD_REGEDIT);
		}
		return false;
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == Constants.REQUEST_PASSWORD_REGEDIT && resultCode==Constants.REQUEST_PASSWORD_SET){
			//password_activity 이후 4자리 값을 받아옴.
			String passwd = data.getExtras().getString(Constants.USER_PASSWORD_STRING);
			etPass.setText(passwd);
		}
	}


	AsyncTaskCompleteListener registListener = new AsyncTaskCompleteListener(){

		@Override
		public void excuteHttpTask() {
			//Url 세팅.
			String url = Util.getUrl("UserRegister");

			//id와 passwd 세팅해줌.
			String id = etID.getText().toString();
			String passwd = etPass.getText().toString();
			String phone = etPhone.getText().toString();
			String regid = CafeNoaPreference.getGcmID(mContext);
			ArrayList<NameValuePair> value = new ArrayList<NameValuePair>();
			value.add(new BasicNameValuePair("USER_ID", id));
			value.add(new BasicNameValuePair("USER_PASSWORD", passwd));
			value.add(new BasicNameValuePair("USER_PHONE", phone));
			value.add(new BasicNameValuePair("USER_GCM_ID", regid));
			
			HttpPostTask http = new HttpPostTask(mContext, value, url, registListener);
			http.execute();
		}

		@Override
		public void onTaskComplete(String result, boolean taskOk) {
			Log.v("result","reuslt :" + result);

			//http 통신 실행후 서버로부터 오는 내용.
			if(taskOk){
				int code = -1;
				String resultString = null;
				int point = 0;
				String userGrade = null;

				try {
					JSONObject object = new JSONObject(result);
					resultString = object.getString("RESULT_STRING");
					code = object.getInt("RESULT");
					point = object.getInt("USER_POINT");
					userGrade = object.getString("USER_GRADE");

				} catch (JSONException e) {
					e.printStackTrace();
				}

				Toast.makeText(mContext, resultString, Toast.LENGTH_LONG).show();
				if(code==-1){
					Log.v("CafeNoa","Server Error No code!");
					return;
				}
				
				if ( code== Constants.NETWORK_SUCCESS ) {
					String id = etID.getText().toString();
					String passwd = etPass.getText().toString();
					//서버와 통신 성공시 프리퍼런스로 아이디를 저장함.
					CafeNoaPreference.setUserID(mContext, id);
					CafeNoaPreference.setUserPassword(mContext, passwd);
					CafeNoaPreference.setUserPoint(mContext, point);
					CafeNoaPreference.setUserGrade(mContext, userGrade);
					Toast.makeText(mContext, "회원가입에 성공하였습니다", Toast.LENGTH_SHORT).show();
					Log.v("CafeNoa","Save User Inform to Server");
					
					Intent intent = new Intent(mContext, MainActivity.class);
					mContext.startActivity(intent);
					finish();
				} else{ 
					if(code == Constants.ID_LOGIN_ERROR)
						Toast.makeText(mContext, "중복되는 아이디가 존재합니다.", Toast.LENGTH_SHORT).show();
					etID.setText("");
					etPass.setText("");
				}
			}
		}
		
	};
}
